package com.pospi.pai.yunpos.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.lany.sp.SPHelper;
import com.pospi.dto.GoodsDto;
import com.pospi.pai.yunpos.login.Constant;
import com.pospi.util.App;
import com.pospi.util.GetData;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by acer on 2018/9/13.
 */

public class SocketUtil {
    private Socket socket;
    private OutputStream outputStream;
    private List<String> msgList = new ArrayList<>();

    public void initThread(final List<GoodsDto> list, final String ip) {
        msgList = changeToCode(list);
//        final String ip = SPHelper.getInstance().getString(Constant.DZC_IP);
        Log.i("ip", ip);
        new Thread(new Runnable() {
            @Override
            public void run() {
                initSocket(ip, 4001);
            }
        }).start();
    }

    public void closeSocket() {
        if (socket != null && outputStream!=null) {
            try {
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void initSocket(final String host, final int port) {
        try {
            socket = new Socket(host, port);//这一步就已经连接上了，
            outputStream = socket.getOutputStream();

//            String ss = stringToHexString("!0V0004A2280081001050000000008020000000000000000000100100000000000000000000000000B186642522294CDE");
//
////            byte[] b1 = strTo16("!0V0002A2280081001050000000008020000000000000000000100100000000000000000000000000B186642522294CDE").getBytes();
//            outputStream.write(b1);
//            outputStream.close();
//            socket.close();
            for (String s : msgList) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                send(s);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void send(String s) {
        byte[] b = hex2byte(stringToHexString(s) + "0D0A");
        Log.i("data", stringToHexString(s) + "0D0A");
        try {
            outputStream.write(b);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i("JAVA", "发送成功:" + s);
    }

    public static String stringToHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }

    private static byte[] hex2byte(String hex) {
        String digital = "0123456789ABCDEF";
        String hex1 = hex.replace(" ", "");
        char[] hex2char = hex1.toCharArray();
        byte[] bytes = new byte[hex1.length() / 2];
        byte temp;
        for (int p = 0; p < bytes.length; p++) {
            temp = (byte) (digital.indexOf(hex2char[2 * p]) * 16);
            temp += digital.indexOf(hex2char[2 * p + 1]);
            bytes[p] = (byte) (temp & 0xff);
        }
        return bytes;
    }


    private String toAreaCode(String word) {

        byte[] bs = new byte[0];
        try {
            bs = word.getBytes("GB2312");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String areaCode = "";
        for (byte b : bs) {
            int code = Integer.parseInt(Integer.toHexString(b & 0xff), 16);
            areaCode += (code - 0x80 - 0x20);       /*transfer the machine code to area code*/
        }
        return areaCode;
    }
    public static StringBuffer getQuwei(String str){
          StringBuffer sb = new StringBuffer();
        byte[] b = new byte[0];
        try {
            b = str.getBytes("gb2312");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int[] quwei = new int[b.length / 2];
          for (int i = 0, k = b.length / 2; i < k; i++) {  
               quwei[i] = (((b[2 * i] - 0xA0) & 0xff) * 100)  
                 + ((b[2 * i + 1] - 0xA0) & 0xff);  
              }  
          for (int i : quwei) {  
               sb.append(i);  
              }  
          return sb;  
         }
    public static boolean NumberCheck(String str) {
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    public String changeToCode(GoodsDto dto) {
        String flag = SPHelper.getInstance().getString(Constant.POS_DZC_FLAG);
        if (flag.length() == 1) {
            flag = flag + "0";
        }
        String plu = dto.getPlu();
        String xh = plu.substring(plu.length() - 4, plu.length());
        String dj = String.format("%06d", (int) (dto.getPrice() * 100));
        String bzts = dto.getBzts();
        if (bzts != null && NumberCheck(bzts)) {
            bzts = String.format("%03d", Integer.parseInt(bzts));
        } else {
            bzts = "001";
        }


        String czfs = dto.getDzc();

        String reg = "[^\u4e00-\u9fa5]";
        String str = dto.getName().replaceAll(reg, "");
        String name = getQuwei(str).toString();
        Log.i("dzc", ">>>>>" + dto.getName());
//                name = "38272591";
        String code = "000000000000000000000000000000000000000000000000";
        String temp = "!0V" + xh + "A22" + plu + dj + czfs + "000000" + bzts + flag + code + "B" +
                name + "CDE";
        Log.i("dzc", plu + "--" + xh + "--" + dj + "--" + czfs + "---" + name);
        return temp;
    }

    private List<String> changeToCode(List<GoodsDto> dtos) {
        String flag = SPHelper.getInstance().getString(Constant.POS_DZC_FLAG);
        if (flag.length() == 1) {
            flag = flag + "0";
        }
        List<String> data = new ArrayList<>();
        //!0V 0001 A 2281080 002000 000000000803000000000000000000000000000000000000000000000000B186642525027C186642525028D186642525028E
        try {
            for (GoodsDto dto : dtos) {
                String plu = dto.getPlu();
                String xh = plu.substring(plu.length() - 4, plu.length());
                String dj = String.format("%06d", (int) (dto.getPrice() * 100));
                String bzts = dto.getBzts();
                if (bzts != null && NumberCheck(bzts)) {
                    bzts = String.format("%03d", Integer.parseInt(bzts));
                } else {
                    bzts = "001";
                }


                String czfs = dto.getDzc();

                String reg = "[^\u4e00-\u9fa5]";
                String str = dto.getName().replaceAll(reg, "");
                String name = getQuwei(str).toString();
                Log.i("dzc", ">>>>>" + dto.getName());
//                name = "38272591";
                String code = "000000000000000000000000000000000000000000000000";
                String temp = "!0V" + xh + "A22" + plu + dj + czfs + "000000" + bzts + flag + code + "B" +
                        name + "CDE";
                Log.i("dzc", plu + "--" + xh + "--" + dj + "--" + czfs + "---" + name);
                data.add(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    //中文转Unicode
    public static String gbEncoding(final String gbString) {   //gbString = "测试"
        char[] utfBytes = gbString.toCharArray();   //utfBytes = [测, 试]
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = Integer.toHexString(utfBytes[byteIndex]);   //转换为16进制整型字符串
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        System.out.println("unicodeBytes is: " + unicodeBytes);
        return unicodeBytes;
    }


}
